/*
 * Copyright (C) 2009 Rob Cash
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ScheduleBuilder.java
 *
 * Created on Jan 2, 2009, 4:46:45 PM
 */

package org.robcash.apps.messagepopup.view.components;

import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.robcash.apps.messagepopup.vo.impl.ScheduleImpl;
import org.robcash.apps.messagepopup.vo.Schedule;

/**
 *
 * @author Rob
 */
public class ScheduleBuilder extends javax.swing.JPanel implements ChangeListener, ListSelectionListener {

    private DefaultListModel listModel = new DefaultListModel();
    private EventListenerList eventListeners;
    private boolean changesPending = false;

    /** Creates new form ScheduleBuilder */
    public ScheduleBuilder() {
        eventListeners = new EventListenerList();
        initComponents();
        scheduleList.getSelectionModel().addListSelectionListener(this);
        scheduleEditor.addChangeListener(this);
    }

    /**
     * Get schedules
     * @return schedules
     */
    public List<Schedule> getSchedules() {
        List<Schedule> schedules = new ArrayList<Schedule>();
        for( int index = 0; index < listModel.getSize(); index++ ) {
            schedules.add((Schedule) listModel.get(index));
        }
        return schedules;
    }
    
    /**
     * Set schedules
     * @param schedules Current list of schedules
     */
    public void setSchedules(List<Schedule> schedules) {
        listModel.clear();
        for( Schedule aSchedule : schedules ) {
            listModel.addElement(aSchedule);
        }
        scheduleList.setSelectedIndex(-1);
    }

    public void stateChanged(ChangeEvent e) {
        if ( e.getSource().equals(scheduleEditor) ) {
            changesPending = true;
            fireChangeListenerStateChanged();
        }
    }

    public void valueChanged(ListSelectionEvent e) {
        if ( !e.getValueIsAdjusting() ) {
            if (changesPending) {
                int status = JOptionPane.showConfirmDialog(this,
                        "Selecting a different schedule will lose pending changes. Continue anyway?");
                if ( status == JOptionPane.YES_OPTION ) {
                    scheduleEditor.setSchedule((Schedule) listModel.get(e.getFirstIndex()));
                    scheduleEditor.setEnabled(true);
                    changesPending = false;
                }
            }
            else {
                scheduleEditor.setSchedule((Schedule) listModel.get(e.getFirstIndex()));
                scheduleEditor.setEnabled(true);
            }
        }
    }

    /**
     * Apply pending changes
     * @return Indicates whether or not changes were successfully applied
     */
    public boolean applyChanges() {
        scheduleEditor.applyPendingChanges();
        changesPending = false;
        return true;
    }
    
    /**
     * Add change listener
     * @param listener Change listener to add
     */
    public void addChangeListener(ChangeListener listener) {
        eventListeners.add(ChangeListener.class, listener);
    }

    /**
     * Remove a change listener
     * @param listener Change listener to remove
     */
    public void removeChangeListener(ChangeListener listener) {
        eventListeners.remove(ChangeListener.class, listener);
    }

    /**
     * Notify listeners that the builder has changed
     */
    protected void fireChangeListenerStateChanged() {
        ChangeListener[] listeners = eventListeners.getListeners(ChangeListener.class);
        ChangeEvent event = new ChangeEvent(this);
        for( int index = 0; index < listeners.length; index++ ) {
            listeners[index].stateChanged(event);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        existingSchedulePanel = new javax.swing.JPanel();
        schedulesLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        scheduleList = new javax.swing.JList();
        addButton = new javax.swing.JButton();
        scheduleEditor = new org.robcash.apps.messagepopup.view.components.ScheduleEditor();

        setName("Form"); // NOI18N

        jSplitPane1.setResizeWeight(0.5);
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        existingSchedulePanel.setName("existingSchedulePanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.robcash.apps.messagepopup.Main.class).getContext().getResourceMap(ScheduleBuilder.class);
        schedulesLabel.setText(resourceMap.getString("schedulesLabel.text")); // NOI18N
        schedulesLabel.setName("schedulesLabel"); // NOI18N

        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        scheduleList.setModel(listModel);
        scheduleList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        scheduleList.setName("scheduleList"); // NOI18N
        jScrollPane1.setViewportView(scheduleList);

        addButton.setText(resourceMap.getString("addButton.text")); // NOI18N
        addButton.setName("addButton"); // NOI18N
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addScheduleButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout existingSchedulePanelLayout = new javax.swing.GroupLayout(existingSchedulePanel);
        existingSchedulePanel.setLayout(existingSchedulePanelLayout);
        existingSchedulePanelLayout.setHorizontalGroup(
            existingSchedulePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(existingSchedulePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(existingSchedulePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                    .addComponent(schedulesLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addButton))
                .addContainerGap())
        );
        existingSchedulePanelLayout.setVerticalGroup(
            existingSchedulePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(existingSchedulePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(schedulesLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(addButton)
                .addContainerGap(156, Short.MAX_VALUE))
        );

        jSplitPane1.setLeftComponent(existingSchedulePanel);

        scheduleEditor.setEnabled(false);
        scheduleEditor.setName("scheduleEditor"); // NOI18N
        jSplitPane1.setRightComponent(scheduleEditor);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 347, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void addScheduleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addScheduleButtonActionPerformed
        Schedule newSchedule = new ScheduleImpl();
        newSchedule.setName("New Schedule");
        ((DefaultListModel) scheduleList.getModel()).addElement(newSchedule);
        scheduleList.setSelectedValue(newSchedule, true);
    }//GEN-LAST:event_addScheduleButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JPanel existingSchedulePanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private org.robcash.apps.messagepopup.view.components.ScheduleEditor scheduleEditor;
    private javax.swing.JList scheduleList;
    private javax.swing.JLabel schedulesLabel;
    // End of variables declaration//GEN-END:variables

}
